//
//  CouponTableViewController.m
//  Truffle
//
//  Created by raca on 05/03/10.
//  Copyright 2010 isrtream1-svn . All rights reserved.
//

#import "CouponTableViewController.h"
#import "CouponDetails.h"
#import "Coupon.h"
#import "ExchangeCouponsViewController.h"
#import "LoadAndSaveCoupons.h"
#import "DatasTruffle.h"
#import "DAOTruffle.h"

@implementation CouponTableViewController


- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    return [super initWithStyle:style];
}


- (void)dealloc {
	NSLog(@"*********** [CouponTableViewController] - [dealloc] - debut de dealloc");
	[couponList release];
    [super dealloc];
}


#pragma mark -

- (void)viewDidLoad {
    [super viewDidLoad];
	UINavigationItem* nav = [self navigationItem];
	[nav setTitle:@"Coupons"];
	[self.navigationItem setRightBarButtonItem:[self editButtonItem]];
	[nav setLeftBarButtonItem:[[UIBarButtonItem alloc]
							   initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
							   target:self action:@selector(receiveCoupon:)]];		
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];	
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
	
	// récupérer la liste des coupons de la passerelle de référence ainsi que de la dernière passerelle 
	// sur laquell j'ai été connecté
	if(![DatasTruffle isConnected]) {
		NSLog(@"application not connected, cannot check for new coupons");
		[self refreshList];
		//exit(1);
	} else {
		// récupérer la liste des coupons de la passerelle de référence
		NSString * currentRefGateWay = [[[DatasTruffle getGateways] objectAtIndex:0] ip]; 
		restConnection = [RestConnection new];
		restConnection.baseURLString = [NSString stringWithFormat:@"%@/iphone/listcoupons", currentRefGateWay];
		LoadAndSaveCoupons *loadAndSaveCoupons = [[LoadAndSaveCoupons alloc] init];
		[loadAndSaveCoupons setRestMyConnection:restConnection];
		[loadAndSaveCoupons setMyCaller:self];
		[loadAndSaveCoupons setGateway:currentRefGateWay];
		restConnection.delegate = loadAndSaveCoupons;
		NSString *urlString = @"";
		[restConnection performRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
		
		// récupérer la liste des coupons de la dernière passerelle de référence sur laquelle 
		// j'ai été connecté
		NSString * lastRefGateWay = [[[DatasTruffle getDao] getRef] ip];
		restConnection = [RestConnection new];
		restConnection.baseURLString = [NSString stringWithFormat:@"%@/iphone/listcoupons", lastRefGateWay];
		loadAndSaveCoupons = [[LoadAndSaveCoupons alloc] init];
		[loadAndSaveCoupons setRestMyConnection:restConnection];
		[loadAndSaveCoupons setMyCaller:self];
		[loadAndSaveCoupons setGateway:lastRefGateWay];
		restConnection.delegate = loadAndSaveCoupons;
		urlString = @"";
		[restConnection performRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
	}	
}


/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [couponList count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    }
    
	Coupon * currentCoupon = [couponList objectAtIndex:[indexPath row]];
	[[cell textLabel] setText:currentCoupon.name];
	
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	CouponDetails* couponDetails = [[CouponDetails alloc] initWithMyCoupon:[couponList objectAtIndex:[indexPath row]]];
	[[self navigationController] pushViewController:couponDetails animated:YES];
	[couponDetails release];
	
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


// editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
	if (editingStyle == UITableViewCellEditingStyleDelete) {
		// suppression du coupon de la base de données
		[[DatasTruffle getDao] removeCoupon:[couponList objectAtIndex:[indexPath row]]];
		// suppression du coupon de la liste des coupons couponList
		[couponList removeObjectAtIndex:[indexPath row]];
		[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
	}   
	else if (editingStyle == UITableViewCellEditingStyleInsert) {
		// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
	}   
}



/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */



#pragma mark -
#pragma mark Private Methods

- (void)receiveCoupon:(id)sender {
	ExchangeCouponsViewController *exchangeCouponsViewController = [[ExchangeCouponsViewController alloc]initWithMyCoupon:nil andPeerStatus:iClient];
	[[self navigationController]pushViewController:exchangeCouponsViewController animated:YES]; 	
	[exchangeCouponsViewController release];
}



- (void) startAlertWithTitle:(NSString*)atitle andMessage:(NSString*)aMessage {
	
	UIAlertView *alert = [[UIAlertView alloc]
						  initWithTitle:atitle
						  message:[NSString stringWithFormat:@"%@", aMessage]
						  delegate:nil
						  cancelButtonTitle:nil
						  otherButtonTitles:@"OK",  nil];
	[alert show];
	[alert release];
}

// TODO delete the following method
- (void)puplateDBOne{
	
	for (int i=0; i<6; i++) {		
		[[DatasTruffle getDao] addCoupon:[[Coupon alloc]initWithId:[NSString stringWithFormat:@"idCoupon.%d",i] 
															  name:[NSString stringWithFormat:@"Coupon.%d",i] 
														  position:[NSString stringWithFormat:@"position.%d",i] 
														  provider:[NSString stringWithFormat:@"provider of coupon.%d",i ] 
														couponCode:[NSString stringWithFormat:@"CODECOUPON.%d",i] 
													  descriptions:[NSString stringWithFormat:@"With the coupon.%d you can do any thing !", i]]];		
	}
}


// TODO delete the following method
- (void)puplateDBTwo{
	for (int i=0; i<6; i++) {
		[[DatasTruffle getDao] addCoupon:[[Coupon alloc]initWithId:[NSString stringWithFormat:@"idCoupon_%d",i] 
															  name:[NSString stringWithFormat:@"Coupon_%d",i] 
														  position:[NSString stringWithFormat:@"position_%d",i] 
														  provider:[NSString stringWithFormat:@"provider of coupon_%d",i ] 
														couponCode:[NSString stringWithFormat:@"CODECOUPON_%d",i] 
													  descriptions:[NSString stringWithFormat:@"With the coupon_%d you can do any thing !", i]]];		
	}
}


- (void)refreshList {
	NSLog(@"*********** [refreshList] debut de refreshList");
	// TODO delete the following line
	//	self.puplateDBOne;	
	
	if (couponList != nil) {
		NSLog(@"*********** [refreshList] couponList est pas nil");
		// c'est pas le premier affichage de cette vue. 
		// couponList est cencé être nil
		for (Coupon *cp in couponList) {
			if (cp !=nil) {
				[cp release];	
			}
		}
	}
	NSLog(@"*********** [refreshList] getCoupons");
	couponList = [[DatasTruffle getDao] getCoupons];
	[self.tableView reloadData];
}
@end

